/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudexapps.manager.actions;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.multipart.MultipartFile;

import uk.ljmu.qudexapps.manager.utilities.Constants;
import uk.ljmu.qudexapps.xmllib.utilities.IngestionResults;

public class EmailActions {
    private JavaMailSender mailSender;
    private VelocityEngine velocityEngine;

    public void setMailSender(JavaMailSender mailSender) {
	this.mailSender = mailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine) {
	this.velocityEngine = velocityEngine;
    }

    public String sendConfirmationEmail(final String emailAdress,
	    final String messageResults,
	    final List<IngestionResults> ingestionResults,
	    final MultipartFile attachment, final String tempDir) {
	String fullPath = "";
	if (attachment != null && attachment.getSize() > 0) {
	    fullPath = (tempDir.endsWith(System
		    .getProperty("file.separator"))) ? tempDir
		    + attachment.getOriginalFilename() : tempDir
		    + System.getProperty("file.separator")
		    + attachment.getOriginalFilename();
	}
	MimeMessagePreparator preparator = new MimeMessagePreparator() {

	    @SuppressWarnings("unchecked")
	    public void prepare(MimeMessage mimeMessage) throws Exception {
		MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
			true);
		message.setTo(emailAdress);
		//message.setFrom(Constants.EMAIL_DEFAULT_ADDRESS);
		@SuppressWarnings("rawtypes")
		Map model = new HashMap();
		model.put("messageResults", messageResults);
		model.put("results", ingestionResults);
		String text = VelocityEngineUtils.mergeTemplateIntoString(
			velocityEngine, "mail-template.vm", model);
		message.setText(text, true);
		message.setSubject(Constants.SUBJECT_EMAIL);
		if (attachment != null && attachment.getSize() > 0) {
		    String fullPath = (tempDir.endsWith(System
			    .getProperty("file.separator"))) ? tempDir
			    + attachment.getOriginalFilename() : tempDir
			    + System.getProperty("file.separator")
			    + attachment.getOriginalFilename();
		    File file = new File(fullPath);
		    writeToFile(attachment.getInputStream(), file);
		    FileSystemResource fileS = new FileSystemResource(file);
		    message.addAttachment(attachment.getOriginalFilename(),
			    fileS);
		}
	    }
	};
	this.mailSender.send(preparator);
	if (fullPath != "") {
	    File file = new File(fullPath);
	    if (!(file.delete()))
		System.out.println("Error while deleting file");
	}
	    
	return "success";
    }

    private void writeToFile(InputStream is, File file) {
	try {
	    DataOutputStream out = new DataOutputStream(
		    new BufferedOutputStream(new FileOutputStream(file)));
	    int c;
	    while ((c = is.read()) != -1) {
		out.writeByte(c);
	    }
	    is.close();
	    out.close();
	} catch (IOException e) {
	    System.err.println("Error Writing/Reading Streams.");
	}
    }
}
